package com.chen.web.servlet;

import com.chen.domain.LoginUser;
import com.chen.domain.RegeditUser;
import com.chen.domain.User;
import com.chen.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
//注册
@WebServlet("/regedit")
public class RegeditServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String role = request.getParameter("role");

        //把网页参数封装成一个对象regeditUser
        RegeditUser regeditUser = new RegeditUser(username, password,role);

        UserService userService = new UserService();
        User regedit = userService.regedit(regeditUser);

        if (regedit != null) {
            //数据库有数据
            request.setAttribute("regedit_error","该用户名已被注册!!!");
            request.getRequestDispatcher("/regedit.jsp").forward(request,response);
        }else {
            //注册成功
            userService.UserAdd(regeditUser);
            //对注册后的数据的处理，向成功的界面给一个用户名的数据
            request.getSession().setAttribute("username", username);
            //转到注册成功页面
            response.sendRedirect(request.getContextPath()+"regeditSuccess.jsp");
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
